package servlet;

import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

@WebServlet("/xls_home4")
public class XLSServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=student_info.xlsx");

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet("Student Info");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] headers = {"学号", "姓名", "性别", "年龄", "所在系"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 添加学生信息行
        String[][] studentData = {
                {"101", "张三", "男", "20", "计算机系"},
                {"102", "李四", "女", "22", "数学系"},
                {"103", "王五", "男", "21", "物理系"}
        };

        for (int i = 0; i < studentData.length; i++) {
            Row dataRow = sheet.createRow(i + 1);
            for (int j = 0; j < studentData[i].length; j++) {
                Cell cell = dataRow.createCell(j);
                cell.setCellValue(studentData[i][j]);
            }
        }

        // 将工作簿写入输出流
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        }

        // 关闭工作簿
        workbook.close();
    }
}
